package elicecn.web.struts2ext.util;

import java.beans.PropertyDescriptor;

import org.apache.commons.beanutils.PropertyUtils;

public class BeanUtils extends PropertyUtils {
	public static void copyProperties(Object dest, Object src) {
		copyProperties(dest, src, true);
	}

	public static void copyProperties(Object dest, Object src, boolean skipNull) {
		if (dest == null) {
			throw new IllegalArgumentException("DEST is null");
		}
		if (src == null) {
			throw new IllegalArgumentException("SRC is null");
		}
		PropertyDescriptor[] origDescriptors = PropertyUtils
				.getPropertyDescriptors(src);
		for (int i = 0; i < origDescriptors.length; i++) {
			String name = origDescriptors[i].getName();
			if ("class".equals(name)) {
				continue;
			}

			if (PropertyUtils.isReadable(src, name)
					&& PropertyUtils.isWriteable(dest, name)) {
				Object value = null;
				try {
					value = PropertyUtils.getSimpleProperty(src, name);
				} catch (Exception e) {
					throw new RuntimeException();
				}
				if (skipNull) {
					if (value == null) {
						continue;
					}
				} else if (value == null) {
					value = null;
				}
				try {
					setProperty(dest, name, value);
				} catch (Exception e) {
					throw new RuntimeException();
				}
			}
		}
	}
}
